package com.metering.purchaseServerAdmin.service.impl;

import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;

import com.metering.purchaseServerAdmin.dao.TokenDao;
import com.metering.purchaseServerAdmin.domain.TokenDO;
import com.metering.purchaseServerAdmin.service.TokenService;

public class TokenServiceImpl implements TokenService {
	@Autowired
    private TokenDao tokenDao;
	
	//过期时间，单位s
    private final static int EXPIRE = 60*30;

	@Override
	public String createToken(Long userId) {
		// TODO Auto-generated method stub
		//当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime()+EXPIRE*1000);
        TokenDO tokenDO = new TokenDO();
        tokenDO.setUserId(userId);
        tokenDO.setUpdateTime(now);
        tokenDO.setToken(UUID.randomUUID().toString());
        tokenDO.setExpireTime(expireTime);
        if(tokenDao.getTokenByUserId(userId)!=null){
            tokenDao.update(tokenDO);
        }else{
            tokenDao.save(tokenDO);
        }

        return tokenDO.getToken();
	}

	@Override
	public Long getUserIdByToken(String token) {
		// TODO Auto-generated method stub
		TokenDO tokenDO = tokenDao.getToken(token);
        if (tokenDO==null){
            return -1L;
        }else {
            if (tokenDO.getExpireTime().getTime()<System.currentTimeMillis()){
                tokenDao.removeToken(token);
                return -1L;
            }
            return tokenDO.getUserId();
        }
	}

	@Override
	public boolean removeToken(String token) {
		// TODO Auto-generated method stub
		return tokenDao.removeToken(token);
	}

}
